<template>
  <teleport to="body">
    <Transition @before-enter="onBeforeEnter" @enter="onEnter" @after-enter="onAfterEnter" @before-leave="onBeforeLeave"
      @leave="onLeave" @after-leave="onAfterLeave">
      <div class="mask" v-show="isVisible" ref="maskRef">
        <div class="container" ref="containerRef">
          <!-- 关闭按钮 -->
          <div class="close-btn" @click="hide">
            <el-icon color="#fe455d" size="25px">
              <CircleCloseFilled />
            </el-icon>
          </div>
          <!-- 左侧图片或者视频展示部分 -->
          <div class="media-container" @mouseover="isHovered = true" @mouseleave="isHovered = false">
            <el-image class="media-image "
              :src="useProductDetailStore().productDetail.image[useProductDetailStore().imageIndex]" fit="contain" />
            <!-- 左箭头 -->
            <Transition name="fade">
              <el-icon v-if="isHovered && useProductDetailStore().productDetail.image.length > 1"
                @click="useProductDetailStore().prev" class="left-arrow">
                <ArrowLeftBold />
              </el-icon>
            </Transition>
            <!-- 右箭头 -->
            <Transition name="fade">
              <el-icon v-if="isHovered && useProductDetailStore().productDetail.image.length > 1"
                @click="useProductDetailStore().next" class="right-arrow">
                <ArrowRightBold />
              </el-icon>
            </Transition>
          </div>
          <!-- 右侧商品详情和交互部分 -->
          <div class="interaction-container">
            <div class="interaction-header">
              <!-- 头像和昵称 -->
              <div class="author-me">
                <div class="info">
                  <img class="avatar-item" :src="useProductDetailStore().productDetail.avatar" alt="" />
                  <span class="name">{{ useProductDetailStore().productDetail?.nickName }}</span>
                </div>
                <!-- 关注与已关注按钮 -->
                <div class="follow-button">
                  <transition name="fade" enter-active-class="animate__animated animate__zoomIn"
                    leave-active-class="animate__animated animate__zoomOut" 
                    @after-leave="onAfterLeave">
                    <!-- 关注商品发布者时显示已关注 ,点击进行取消关注-->
                    <button class="followed" v-if="useProductDetailStore().isFollowed"
                      @click="useProductDetailStore().addFollow(useProductDetailStore().productDetail.userId, false)">
                      已关注
                    </button>
                    <!-- 商品不是自己的且没有关注商品发布者时显示关注 ,点击进行关注-->
                    <button v-else-if="useUserStore().user.id !== useProductDetailStore().productDetail.userId"
                      @click="useProductDetailStore().addFollow(useProductDetailStore().productDetail.userId, true)">
                      关注
                    </button>
                  </transition>
                </div>
              </div>
            </div>
            <!-- 标题 -->
            <div class="title">
              {{ useProductDetailStore().productDetail.title }}
            </div>
            <!-- 和商品描述 -->
            <div class="intro">
              {{ useProductDetailStore().productDetail.intro }}
            </div>
            <!-- 发货方式和发布时间 -->
            <div class="post-container">
              <span>发货方式： {{ useProductDetailStore().productDetail.postType === 0 ? '邮寄' : '自提' }}</span>
              <span style="margin-top: 10px;">{{ useProductDetailStore().productDetail.createTime }}</span>
            </div>
            <!-- 价格和购买按钮 -->
            <div class="price-want">
              <div class="price">
                <span style="color: red; font-weight: 600; font-size: 20px;">￥{{
                  useProductDetailStore().productDetail.price }}</span>
                <span style="font-size: 14px; color: #666666; text-decoration: line-through;">￥{{
                  useProductDetailStore().productDetail.originalPrice }}</span>
              </div>
              <!-- 查看自己发布的商品不显示购买按钮 -->
              <button v-if="useUserStore().user.id !== useProductDetailStore().productDetail.userId" @click="buy()">购
                买</button>
            </div>
            <el-divider />
            <!-- 评论部分 -->
            <Comment />
            <!-- 底部发布评论 -->
            <div class="interactions-footer">
              <!-- 进行回复时展示回复对象 -->
              <div v-if="useProductDetailStore().isReply" class="reply-user ">
                <span>回复：{{ useProductDetailStore().replyUserNickname }}</span>
                <el-icon size="12px" class="cancel-icon" @click="useProductDetailStore().clearReplyComment()">
                  <CircleClose />
                </el-icon>
              </div>
              <div class="main">
                <!-- 输入框 -->
                <div class="input-wrapper">
                  <el-input v-model="useProductDetailStore().commentDto.content" type="textarea" autosize
                    placeholder="说点什么..." />
                  <!-- 发送按钮 -->
                  <el-button :disabled="useProductDetailStore().commentDto.content === ''" color="#fe3b55" circle
                    style="margin-left: 10px;" @click="useProductDetailStore().addComment">发 送</el-button>
                </div>
                <!-- 收藏 -->
                <div class="like">
                  <!-- 已收藏状态 ,点击取消收藏-->
                  <transition name="fade" enter-active-class="animate__animated animate__zoomIn"
                    leave-active-class="animate__animated animate__zoomOut"
                    @after-leave="onAfterLeave">  
                    <span v-if="useProductDetailStore().isCollected"
                      @click="useProductDetailStore().deleteProductCollect(useProductDetailStore().productDetail.id)">
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-shoucang"></use>
                      </svg>
                      <span style="margin-left: 5px;font-size: 12px;">已收藏</span>
                    </span>
                    <!-- 未收藏状态 ,点击收藏-->
                    <span v-else
                      @click="useProductDetailStore().addProductCollect(useProductDetailStore().productDetail.id)">
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-shoucangjia"></use>
                      </svg>
                      <span style="margin-left: 5px;font-size: 12px;">收藏</span>
                    </span>
                  </transition>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
    <!-- 聊天窗口 -->
    <el-drawer class="custom-drawer" v-model="showDrawer" :with-header="false" :destroy-on-close="true"
      :lock-scroll="false" :size="'500px'">
      <ChatMessage v-if="showDrawer" />
    </el-drawer>
  </teleport>
</template>


<script setup lang='ts'>
import { ref, watch } from 'vue'
import { CircleClose } from '@element-plus/icons-vue'
import ChatMessage from '@/components/message/ChatMessage.vue'
import { CircleCloseFilled, ArrowRightBold, ArrowLeftBold } from '@element-plus/icons-vue'
import { useChatMessageStore, useProductDetailStore, useUserStore } from '@/stores'
import Comment from './Comment.vue'

interface CardPosition {
  x: number
  y: number
  width: number
  height: number
}

// 点击位置
const cardPosition = ref<CardPosition | null>(null)
// 控制抽屉的显示和隐藏
const showDrawer = ref(false)
// 是否可见
const isVisible = ref<boolean>(false)
// 鼠标悬浮状态
const isHovered = ref<boolean>(false)
// DOM引用
const maskRef = ref<HTMLElement>()
const containerRef = ref<HTMLElement>()

// 展示和关闭商品详情组件
const show = (position?: CardPosition) => {
  cardPosition.value = position || null
  isVisible.value = true
}

const hide = () => {
  // 清空回复的评论
  useProductDetailStore().resetStore()
  isVisible.value = false
}

// 动画处理函数
const onBeforeEnter = (el: Element) => {
  const container = containerRef.value
  if (container && cardPosition.value) {
    // 计算缩放比例
    const scale = cardPosition.value.width / container.offsetWidth
    // 计算位置偏移
    const translateX = cardPosition.value.x - (window.innerWidth - container.offsetWidth) / 2
    const translateY = cardPosition.value.y - (window.innerHeight - container.offsetHeight) / 2

    container.style.transformOrigin = '0 0'
    container.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`
    container.style.opacity = '1'
  } else {
    // 如果没有卡片位置信息，从中心缩放
    if (container) {
      container.style.transformOrigin = 'center center'
      container.style.transform = 'scale(0.1)'
      container.style.opacity = '0'
    }
  }
  (el as HTMLElement).style.backgroundColor = 'rgba(0, 0, 0, 0)'
}

// const onEnter = (el: Element, done: () => void) => {
//   // 强制重绘
//   (el as HTMLElement).offsetHeight
//   const container = containerRef.value
//   if (container) {
//     // 增加动画时长到 0.5s，使用更平滑的贝塞尔曲线s
//     container.style.transition = 'all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1)'
//     container.style.transform = 'translate(0, 0) scale(1)'
//     container.style.opacity = '1'
//   }
//   // 背景遮罩的过渡也相应调整
//   (el as HTMLElement).style.transition = 'background-color 0.5s';
//   (el as HTMLElement).style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
//   // 等待动画完成
//   setTimeout(done, 500)
// }
const onEnter = (el: Element, done: () => void) => {
  // 强制重绘
  (el as HTMLElement).offsetHeight
  const container = containerRef.value
  if (container) {
    // 保持500ms的过渡时间
    container.style.transition = 'all 5s cubic-bezier(0.34, 1.56, 0.64, 1)'
    container.style.transform = 'translate(0, 0) scale(1)'
    container.style.opacity = '1'
  }
  // 背景遮罩的过渡也调整为500ms
  (el as HTMLElement).style.transition = 'background-color 0.5s';
  (el as HTMLElement).style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
  // 等待时间设置为500ms，与transition时间一致
  setTimeout(done, 500)
}

const onLeave = (el: Element, done: () => void) => {
  (el as HTMLElement).style.backgroundColor = 'rgba(0, 0, 0, 0)'
  // 等待时间也设置为500ms，保持一致
  setTimeout(done, 200)
}

const onAfterEnter = () => {
  const container = containerRef.value
  if (container) {
    container.style.transition = ''
  }
}

const onBeforeLeave = (el: Element) => {
  const container = containerRef.value
  if (container && cardPosition.value) {
    // 计算缩放比例
    const scale = cardPosition.value.width / container.offsetWidth
    // 计算位置偏移
    const translateX = cardPosition.value.x - (window.innerWidth - container.offsetWidth) / 2
    const translateY = cardPosition.value.y - (window.innerHeight - container.offsetHeight) / 2

    container.style.transition = 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)'
    container.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`
  } else if (container) {
    container.style.transition = 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)'
    container.style.transform = 'scale(0.1)'
  }
  (el as HTMLElement).style.transition = 'background-color 0.3s'
}

// const onLeave = (el: Element, done: () => void) => {
//   (el as HTMLElement).style.backgroundColor = 'rgba(0, 0, 0, 0)'
//   setTimeout(done, 300)
// }

const onAfterLeave = () => {
  const container = containerRef.value
  if (container) {
    container.style.transform = ''
    container.style.opacity = ''
    container.style.transition = ''
  }
  // 清除位置信息
  cardPosition.value = null
}

// 暴露给外部的方法
defineExpose({
  show,
})

// 购买按钮点击事件
const buy = () => {
  if (useUserStore().Authorization === null) {
    // 未登录跳转到登录页面
    ElMessage.warning('请先登录')
    return
  }
  showDrawer.value = true
}

// 监听 isVisible，showDrawer为 true 时初始化 data
watch(showDrawer, (newShowDrawer) => {
  // showDrawer为 true 时初始化获取聊天记录
  if (newShowDrawer) {
    // 获取对应商品和商品发布者的聊天记录（有就获取，没有就不管）
    useChatMessageStore().getChatDetail(useProductDetailStore().productDetail.id, useProductDetailStore().productDetail.userId)
  }
})
</script>

<style lang='less' scoped>
.mask {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: all;
  z-index: 2;
  will-change: background-color;

  .container {
    width: auto;
    max-width: calc(var(--view-width) * 0.9);
    height: calc(var(--view-height) * 0.9);
    background-color: var(--background-color);
    position: relative;
    border-radius: 15px;
    display: flex;
    will-change: transform, opacity;
    backface-visibility: hidden;
    transform-style: preserve-3d;
    overflow: hidden;

    .close-btn {
      position: absolute;
      right: 5px;
      top: 5px;
      cursor: pointer;
      transition: all 0.2s;
      z-index: 3;

      &:hover {
        transform: scale(1.2);
      }
    }

    .media-container {
      width: auto; // 宽度由内容决定
      height: calc(var(--view-height) * 0.9); // 高度固定
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 15px;
      position: relative;

      .media-image {
        height: 100%;
        max-width: calc(var(--view-width) * 0.55);
        border-radius: 15px 0 0 15px;
      }

      .left-arrow {
        position: absolute;
        left: 2%;
        top: 50%;
        color: #ffffff;
        font-size: 24px;
        transform: translateY(-50%);
        cursor: pointer;
        transition: all 0.2s;

        &::before {
          content: '';
          position: absolute;
          width: 40px;
          height: 40px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          z-index: -1;
          transition: all 0.5s;
          /* 设置过渡时间为0.5秒 */
        }

        &:hover {
          transform: translateY(-50%) scale(1.1);
          /* 保持居中，原地放大 */
        }
      }

      .right-arrow {
        position: absolute;
        right: 2%;
        top: 50%;
        color: #ffffff;
        font-size: 24px;
        transform: translateY(-50%);
        cursor: pointer;
        transition: all 0.2s;

        &::before {
          content: '';
          position: absolute;
          width: 40px;
          height: 40px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          z-index: -1;
          transition: all 0.5s;
          /* 设置过渡时间为0.5秒 */
        }

        &:hover {
          transform: translateY(-50%) scale(1.1);
          /* 保持居中，原地放大 */
        }
      }
    }

    .interaction-container {
      width: calc(var(--view-width) * 0.35);
      overflow: auto;
      position: relative;

      &::-webkit-scrollbar {
        display: none;
      }

      .interaction-header {
        position: sticky;
        top: 0;
        padding: 10px 20px;
        border-radius: 0 15px 0 0;
        width: calc(var(--view-width) * 0.35);
        background-color: #fff;
        border-bottom: 1px solid var(--color-border);
        z-index: 1;

        .author-me {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .info {
            display: flex;
            align-items: center;

            .avatar-item {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              margin-right: 10px;
            }

            .name {
              font-size: 16px;
              font-weight: 600;
              color: var(--dark-font-color);
            }
          }

          .follow-button {
            display: flex;
            justify-content: center;
            align-items: center;

            button {
              width: 60px;
              height: 30px;
              margin-right: 20px;
              background-color: var(--theme-color);
              color: #ffffff;
              border: none;
              font-size: 14px;
              border-radius: 20px;
              font-weight: 700;
              cursor: pointer;
              transition: all 0.2s;
            }

            button:hover {
              transform: scale(1.05);
            }

            .followed {
              background: rgba(var(--theme-color-rgb), 0.1);
              color: var(--theme-color);
              border: 1px solid rgba(var(--theme-color-rgb), 0.4);
            }
          }
        }
      }

      .title {
        margin: 20px 0 0 20px;
        font-weight: 700;
        font-size: 18px;
      }

      .intro {
        margin: 10px 20px;
        min-height: 60px;
        max-height: 120px;
        font-weight: 400;
        font-size: 16px;
        line-height: 150%;
        color: var(--dark-font-color);
        white-space: pre-wrap;
        overflow-wrap: break-word;
        overflow: auto;

        &::-webkit-scrollbar {
          width: 5px;
          /* 滚动条宽度 */
        }

        &::-webkit-scrollbar-thumb {
          background-color: rgba(254, 59, 85, 0.9);
          /* 滚动条颜色 */
          border-radius: 10px;
          /* 滚动条圆角 */
        }

        &::-webkit-scrollbar-track {
          background-color: var(--dark-background-color);
          /* 滚动条轨道颜色 */
        }

        &::-webkit-scrollbar-button {
          display: none;
          /* 隐藏上下按钮 */
        }
      }

      .post-container {
        display: flex;
        flex-direction: column;
        margin: 10px 20px;
        font-weight: 400;
        font-size: 14px;
        color: var(--dark-font-color);
        white-space: pre-wrap;
        overflow-wrap: break-word;
      }

      .price-want {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 10px 20px;

        .price {
          height: 40px;
          line-height: 40px;
        }

        button {
          width: 60px;
          height: 30px;
          margin-right: 20px;
          background-color: var(--theme-color);
          color: #ffffff;
          border: none;
          font-size: 14px;
          border-radius: 15px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.2s;
        }

        button:hover {
          transform: scale(1.05);
        }
      }

      .el-divider--horizontal {
        margin: 10px 0;
      }

      .interactions-footer {
        position: sticky;
        bottom: 0;
        width: calc(var(--view-width) * 0.35);
        background-color: #fff;
        min-height: 50px;
        height: auto;
        border-radius: 0 0 15px 0;
        padding: 10px 20px;
        border-top: 1px solid #e7e3e3;

        .reply-user {
          height: 30px;
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #666666;
          margin-bottom: 10px;

          .cancel-icon {
            margin-left: 10px;
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
              transform: scale(1.2);
            }
          }
        }

        .main {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .input-wrapper {
            display: flex;
            align-items: center;

            :deep(.el-textarea__inner) {
              background-color: var(--dark-background-color);
              border-radius: 20px;
              padding-left: 20px;
              box-shadow: none;
              resize: none;
              caret-color: var(--theme-color);
            }

            button {
              width: 60px;
              height: 30px;
              border: none;
              font-size: 14px;
              border-radius: 15px;
              font-weight: 600;
              transition: all 0.2s;

              &:hover {
                transform: scale(1.05);
              }
            }
          }

          .like {
            display: flex;
            align-items: center;

            .icon {
              width: 1.5em;
              height: 1.5em;
              vertical-align: -0.35em;
              fill: currentColor;
              overflow: hidden;
              transition: all 0.2s;

              &:hover {
                cursor: pointer;
                transform: scale(1.1);
              }
            }
          }
        }


      }

    }
  }
}
</style>
